import { Forward } from "@/api/interface/iot";
import { addServer, modServer, getServerList, delServer, testServer } from "@/api/modules/forward/forwardServer";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { PASSWORD_KEY } from "@/config/config";
import { MessageType } from "@/enums/messageEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { decrypt, encrypt } from "@/utils/encrypt";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import BasicDialog from "./components/serverDialog";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
import "./forwardServer.scss";

export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const key = ref<any>(PASSWORD_KEY);
		const initParam = reactive<Forward.ReqServer>({});
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			params.type = state.active;
			return getServerList(params);
		};
		const btnList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			btnList.value = await useAuthButtons();
		});
		const detailDialog = reactive<any>({
			title: proxy?.$t("forwardserver.dialog_title.add"),
			detail: {},
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			let selected = row.selectList || [row];
			switch (fn) {
				case "mod":
				case "details":
					if (selected.length != 1) {
						showMsg(proxy?.$t("forwardserver.msg.details"), MessageType.warning);
						return;
					}
					detailDialog.detail = { ...selected[0], type: state.active };
					detailDialog.detail.password = decrypt(detailDialog.detail.password, key.value, key.value);
					detailDialog.title = proxy?.$t("forwardserver.dialog_title.edit");
					detailDialog.visible = true;
					break;
				case "add":
					detailDialog.detail = { type: state.active };
					detailDialog.title = proxy?.$t("forwardserver.dialog_title.new");
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("forwardserver.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("forwardserver.confirm.del") }).then(flag => {
						flag && submitDel({ id: selected.map((item: any) => item.id).join(",") });
					});
					break;
				case "tester":
					if (selected.length != 1) {
						showMsg(proxy?.$t("forwardserver.msg.tester"), MessageType.warning);
						return;
					}
					let { code, message } = await testServer({ id: selected[0].id });
					showTips(code, proxy?.$t("forwardserver.tips.tester"), message);
					break;
			}
		};
		const state = reactive({
			active: "MQTT",
			tabs: [
				{ key: "MQTT", label: proxy?.$t("forwardserver.tabs.mqtt") },
				{ key: "HTTP", label: proxy?.$t("forwardserver.tabs.http") },
				{ key: "DB", label: proxy?.$t("forwardserver.tabs.db") }
			]
		});
		const changeTableType = () => {
			if (state.active == "HTTP") {
				columns = columns.map((item: ColumnProps) => {
					if (item.prop == "connectStatus") {
						item.label = proxy?.$t("forwardserver.tablist_label.last");
					}
					if (item.prop == "url") {
						item.isShow = true;
					}
					return item;
				});
			} else {
				columns = columns.map((item: ColumnProps) => {
					if (item.prop == "connectStatus") {
						item.label = proxy?.$t("forwardserver.tablist_label.connect_status");
					}
					if (item.prop == "url") {
						item.isShow = false;
					}
					return item;
				});
			}
			proTable.value.clearSelection();
			proTable.value.getTableList();
		};

		// 表格配置项
		let columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "connectStatus", label: proxy?.$t("forwardserver.tablist_label.connect_status"), width: 100 },
			{ prop: "name", label: proxy?.$t("forwardserver.tablist_label.name"), search: { el: "input" } },
			{ prop: "host", label: proxy?.$t("forwardserver.tablist_label.host"), search: { el: "input" } },
			{ prop: "port", label: proxy?.$t("forwardserver.tablist_label.port"), width: 100 },
			{ prop: "url", label: proxy?.$t("forwardserver.tablist_label.url"), isShow: false },
			{ prop: "lastForwardTime", label: proxy?.$t("forwardserver.tablist_label.lasttime"), width: 180 },
			{ prop: "forwardCount", label: proxy?.$t("forwardserver.tablist_label.count"), width: 100 },
			{ prop: "operation", label: proxy?.$t("forwardserver.tablist_label.operation"), fixed: "right", width: 180 }
		];

		const proTable = ref<any>();
		const submitDel = async (dataInfo: any) => {
			let res = await delServer({ ...dataInfo });
			let ok = showTips(res.code, proxy?.$t("forwardserver.tips.del"), res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submit = async () => {
			detailDialog.detail.port = parseInt(detailDialog.detail.port);
			detailDialog.detail.password = encrypt(detailDialog.detail.password, key.value, key.value);
			let api = detailDialog.detail.id ? modServer : addServer;
			let res = await api(detailDialog.detail);
			let ok = showTips(res.code, proxy?.$t("forwardserver.tips.save"), res.message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		return () => {
			return (
				<div class="forward-server">
					{detailDialog.visible && (
						<BasicDialog
							width="600px"
							title={detailDialog.title}
							v-model:visible={detailDialog.visible}
							detail={detailDialog.detail}
							onSubmit={() => {
								submit();
							}}
						></BasicDialog>
					)}
					<el-tabs v-model={state.active} onTabChange={() => changeTableType()} class="bg-white pl-4 pr-4 pt-4">
						{state.tabs.map(item => {
							return <el-tab-pane label={item.label} name={item.key}></el-tab-pane>;
						})}
					</el-tabs>
					<ProTable
						ref={proTable}
						title={btnList.value.length ? "" : proxy?.$t("forwardserver.tab_title.manage")}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							tableHeader: (scope: any) => {
								return btnList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							lastForwardTime: (scope: any) => {
								return dataFormat("datetime", scope.row.lastForwardTime);
							},
							connectStatus: (scope: any) => {
								let status = scope.row.connectStatus == "true";
								return (
									<OnlineStatus
										v-model={status}
										onlineLabel={proxy?.$t("forwardserver.status.online")}
										offlineLabel={proxy?.$t("forwardserver.status.offline")}
									/>
								);
							},
							operation: (scope: any) => {
								return (
									<>
										{btnList.value
											.filter((item: any) => item.path == "del")
											.map((item: any) => {
												return (
													<el-popconfirm
														title={proxy?.$t("forwardserver.popconfirm.title")}
														popper-class="jsonform-tooltip"
														onConfirm={() => submitDel({ id: scope.row.id })}
													>
														{{
															reference: () => {
																return (
																	<el-link type="danger">
																		<i class="iconfont icontrash-2"></i>
																		{item.menuName}
																	</el-link>
																);
															}
														}}
													</el-popconfirm>
												);
											})}
										<el-link type="primary" class="iconfont iconbx-transfer" onClick={() => clickBtn("tester", scope.row)}>
											{proxy?.$t("forwardserver.btn.test")}
										</el-link>
										<el-link type="primary" class="iconfont iconbx-file" onClick={() => clickBtn("details", scope.row)}>
											{proxy?.$t("forwardserver.btn.detail")}
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<Empty
										subtitle={proxy?.$t("forwardserver.empty.subtitle")}
										btnText={proxy?.$t("forwardserver.empty.btn_text")}
										onAdd={() => clickBtn("add", {})}
									/>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
